<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>栈的封装</title>
</head>
<body>


<script>
    //封装栈类
    function Stack() {
        //栈中的属性
        this.item = []

    }
    /*栈的相关操作*/
    //1.将元素压入栈
    Stack.prototype.push = function (element) {
        this.item.push(element)
    };

    //2.从栈中取出元素(栈顶元素，对于数组说是最后一个元素)
    Stack.prototype.pop = function () {
        return this.item.pop() //移除数组中的最后一项并返回该项
    };

    //3.查看一下栈顶元素
    Stack.prototype.peek = function () {
        return this.item[this.item.length - 1]
    };

    //4.判断栈是否为空
    Stack.prototype.isEmpty = function () {
        return this.item.length == 0
    };

    //5.获取栈中元素的个数
    Stack.prototype.size = function () {
        return this.item.length
    };

    //6.toString方法
    Stack.prototype.toString = function () {
        let resultString = '';
        for(let i = 0; i < this.item.length; i++) {
            resultString +=this.item[i] + ','
        }
        return resultString
    };

    //栈的使用
    let s = new Stack();
   /* s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    alert(s.toString())*/

   // 函数：十进制转二进制
   function dec2bin(decNumber) {
       // 1.定义栈对象
       let stack = new Stack();
       // 2.循环递归
       while (decNumber > 0) {
           stack.push(decNumber % 2)
           decNumber = Math.floor(decNumber / 2);
       }
       // 3.从栈中取出0和1
       let binary = '';
       while(!stack.isEmpty()) {
           binary += stack.pop()
       }
       return binary;
   }
   
</script>
</body>
</html>